//获得文件行数的方法
// 有 bufferedReader.readLine 方法 或者查找byte是否=='\n',比较谁快！
import java.io.File;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;

public class test {
    public static void main(String[] args) {
        String filePath = "C:\\Users\\张睿\\Desktop\\chaoxian.txt"; // 替换为你的文件路径

        // 方法1: 使用BufferedReader.readLine()
        long startTime1 = System.nanoTime();
        long lineCount1 = countLinesUsingReadLine(filePath);
        long endTime1 = System.nanoTime();

        // 方法2: 手动读取字节并检查换行符
        long startTime2 = System.nanoTime();
        long lineCount2 = countLinesUsingBytes(filePath);
        long endTime2 = System.nanoTime();

        // 输出结果
        System.out.println("使用BufferedReader.readLine()方法得到的行数: " + lineCount1);
        System.out.println("使用BufferedReader.readLine()方法的时间: " + TimeUnit.NANOSECONDS.toMillis(endTime1 - startTime1) + " ms");
        System.out.println("手动读取字节方法得到的行数: " + lineCount2);
        System.out.println("手动读取字节方法的时间: " + TimeUnit.NANOSECONDS.toMillis(endTime2 - startTime2) + " ms");
    }

    private static long countLinesUsingReadLine(String filePath) {
        try (BufferedReader reader = Files.newBufferedReader(Paths.get(filePath))) {
            String line;
            long count = 0;
            while ((line = reader.readLine()) != null) {
                count++;
            }
            return count;
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }

    private static long countLinesUsingBytes(String filePath) {
        try (InputStream inputStream = new FileInputStream(filePath);
             BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {
            int byteRead;
            long count = 0;
            while ((byteRead = bufferedReader.read()) != -1) {
                if (byteRead == '\n') {
                    count++;
                }
            }
            return count;
        } catch (IOException e) {
            e.printStackTrace();
            return -1;
        }
    }
}